package com.example.thread.base.demo3;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2020/12/14 22:35
 * 阻塞队列（特殊情况下） volatile 修饰词  停止进程 （无法停止）
 */
@Slf4j
public class Demo3_3 {
    public static void main(String[] args) throws Exception{
        ArrayBlockingQueue storage = new ArrayBlockingQueue(8);
        Producer producer=new Producer(storage);
        Thread producerThread=new Thread(producer);
        producerThread.start();
        Consumer consumer=new Consumer(storage);
        while (consumer.needMoreNums()){
            System.out.println(consumer.storage.take()+"被消费了");
            Thread.sleep(100);
        }
        System.out.println("消费者不需要数据了");
        //停止线程
        producer.cancle =true;
        System.out.println(producer.cancle);
    }
}
class Consumer {
    BlockingQueue storage;
    public Consumer(BlockingQueue storage) {
        this.storage = storage;
    }
    public boolean needMoreNums() {
        if (Math.random() > 0.97) {
            return true;
        }
        return false;
    }
}

class Producer implements Runnable {
    public volatile boolean cancle = false;
    BlockingQueue storage;
    public Producer(BlockingQueue storage) {
        this.storage = storage;
    }
    @Override
    public void run() {
        int num = 0;
        int numLimit = 100000;
        try {
            while (!cancle && num <= numLimit) {
                if (num % 50 == 0) {
                    storage.put(num);
                    System.out.println("是50的倍数：" + num);
                }
                num++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("生产者结束运行");
        }
    }
}


